import { ApplicationManager, IndexedCache, WorkerManager } from '@yeying-community/yeying-next'
import {
    AssetProvider,
    Downloader,
    LinkProvider,
    NamespaceProvider,
    RecycleProvider,
    ServiceCodeEnum,
    Uploader,
    UserProvider
} from '@yeying-community/yeying-client-ts'

import { $account } from '@yeying-community/yeying-wallet'
import { ProviderOption } from '@yeying-community/yeying-client-ts/src/client/common/model.ts'
import { SecurityAlgorithm } from '@yeying-community/yeying-web3'
import { ApplicationState } from '@yeying-community/yeying-next/dist/types/state/application'

type UserInfo =
    | undefined
    | {
          metadata?: {
              avatar?: string
          }
          [key: string]: any // 允许其他属性
      }
let namespaceProvider: NamespaceProvider
let assetProvider: AssetProvider
let downloader: Downloader
let uploader: Uploader
let linkProvider: LinkProvider
let recycleProvider: RecycleProvider
let workerManager: WorkerManager
let userProvider: UserProvider
let applicationManager: ApplicationManager
let indexedCache: IndexedCache
let applicationState: ApplicationState
let userInfo: UserInfo

// 初始化提供者
async function initializeProviders() {
    const identity = await $account.getActiveIdentity()

    const did = identity?.metadata?.did
    let blockAddress = null
    if (did) {
        blockAddress = await $account.getBlockAddress(did)
    }

    if (!blockAddress) return

    const warehouse = await $account.getServicesByCode(ServiceCodeEnum.SERVICE_CODE_WAREHOUSE)
    const securityAlgorithm = identity?.securityConfig?.algorithm as SecurityAlgorithm
    const providerOption: ProviderOption = {
        proxy: warehouse[0].proxy as string,
        blockAddress: blockAddress
    }
    userInfo = identity //用于头像展示
    userProvider = new UserProvider(providerOption) //  提供用户管理功能的类，支持添加、查询、更新和删除用户
    namespaceProvider = new NamespaceProvider(providerOption) // 命名空间提供者类，用于管理命名空间
    assetProvider = new AssetProvider(providerOption) // 提供对资产的管理，包括查询、版本获取、详情查看、删除等操作
    downloader = new Downloader(providerOption, securityAlgorithm) // 用于下载资产数据，支持从区块提供者获取数据并进行解密
    uploader = new Uploader(providerOption, securityAlgorithm) // 上传资产文件，通过将文件分块后上传，每个块加密（可选）并生成哈希值，最后对整个资产进行签名
    linkProvider = new LinkProvider(providerOption) // 资产分享链接的管理
    recycleProvider = new RecycleProvider(providerOption) // 区块链交互，提供数据的获取和存储功能
    workerManager = new WorkerManager({
        providerOption: providerOption,
        securityAlgorithm: securityAlgorithm
    }) // 使用worker上传和下载资产，并将下载信息存储在indexeddb中
    applicationManager = new ApplicationManager() // 管理当前应用信息
    applicationState = await applicationManager.getCurrentState(did as string)
    indexedCache = new IndexedCache('yeying-assets', 1)
    await indexedCache.open([
        {
            name: 'uploader',
            key: 'workerId',
            autoIncrement: false,
            indexes: [{ keyPath: 'finished', name: 'finished', unique: false }]
        },
        {
            name: 'downloader',
            key: 'workerId',
            autoIncrement: false,
            indexes: [{ keyPath: 'finished', name: 'finished', unique: false }]
        }
    ])
}

export {
    userInfo,
    userProvider,
    namespaceProvider,
    assetProvider,
    downloader,
    uploader,
    linkProvider,
    recycleProvider,
    workerManager,
    applicationState,
    initializeProviders,
    indexedCache
}
